import { ReactiveFlags, isProxy, isReactive, reactive } from "./reactive";
import { track, trigger } from "./effect";
import { hasChanged, isObject } from "../utils";
//

function createGetter(isReadonly = false, isShallow = false) {
  return function get(target, key, receiver) {
    if (key === ReactiveFlags.IS_REACTIE) {
      return !isReadonly;
    } else if (key === ReactiveFlags.IS_READONLY) {
      return isReadonly;
    }

    if (!isReadonly) {
      track(target, "get", key);
    }

    let res = Reflect.get(target, key, receiver);

    if (!isShallow) {
      return isReactive(res) ? res : reactive(res);
    }

    // 对深层次的对象进行追踪
    if (isObject(res)) {
      res = isReadonly(res) ? res : reactive(res);
    }

    return res;
  };
}

function createSetter() {
  return function set(target, key, value, receiver) {
    const oldValue = target[key];

    if (hasChanged(oldValue, value)) {
      Reflect.set(target, key, value, receiver);
      trigger(target, "set", key, value, oldValue);
    }

    return true;
  };
}

function createReadonlySetter() {
  return function set(target, key, value) {
    console.warn(`只读属性: ${key} 不允许修改为 ${value}`);
    return true;
  };
}

const get = createGetter();
const set = createSetter();
const readonlyGetter = createGetter(true);
const shallowGetter = createGetter(false, true);
const shallowReadonlyGetter = createGetter(true, true);
const readonlySetter = createSetter();

export const mutableHandler = { get, set };
export const readonlyHandler = {
  get: readonlyGetter,
  set: readonlySetter,
};
export const shallowHandler = {
  get: shallowGetter,
  set,
};

export const shallowReadonlyHandler = {
  get: readonlyGetter,
  set: readonlySetter,
};
